package com.example.ss.service;

import org.springframework.http.MediaType;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Service;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Author: xwg
 * @CreateDate: 2023/8/25
 */

@Service
public class AuthFailure implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(
            HttpServletRequest request,
            HttpServletResponse response,
            AuthenticationException exception) throws IOException, ServletException {
        response.setStatus(666);
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
//        response.setContentType("application/json;charset=UTF-8");
        PrintWriter writer = response.getWriter();
        if (exception instanceof BadCredentialsException) {
            writer.println("用户名不存在或用户名密码不匹配");
        } else {
            writer.println("登录异常，未知错误");
        }

    }
}
